﻿using Negocio.AccesoDatos;
using Negocio.Entidades;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.UI;
using System.Reflection;

namespace AutogestionAVEIT
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {
            if (HttpContext.Current.User != null)
            {
                ScriptManager.ScriptResourceMapping.AddDefinition("jquery", new ScriptResourceDefinition
                {
                    Path = "~/js/jquery.js",
                    DebugPath = "~/js/jquery.js",
                    CdnSupportsSecureConnection = true,
                    //LoadSuccessExpression = "window.jQuery"
                });
                Application["CantidadUsuarios"] = 0; 
            }
            
            
        }

        protected void Session_Start(object sender, EventArgs e)
        {
            Application.Lock();
            int cantidadUsuarios = Convert.ToInt32(Application["CantidadUsuarios"]);
            cantidadUsuarios++;
            Application["CantidadUsuarios"] = cantidadUsuarios;
            Application.UnLock();
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            
        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            if (HttpContext.Current.User != null)
            {
                if (HttpContext.Current.User.Identity.AuthenticationType == "Forms")
                {                    
                    String[] roles = new String[2];
                    FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
                    List<Rol> l = UsuarioDAO.ObtenerRol(id.Name);
                    for(int i=0; i<l.Count;i++)
                    {
                        roles[i] = l[i].descripcion;
                        HttpContext.Current.User = new GenericPrincipal(id, roles);
                    }
                    
                }
            }

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {
            Application.Lock();
            int cantidadUsuarios = Convert.ToInt32(Application["CantidadUsuarios"]);
            cantidadUsuarios--;
            Application["CantidadUsuarios"] = cantidadUsuarios;
            Application.UnLock();
            Application.RemoveAll();

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }
}